package com.way.demo.comm;

import cn.hutool.core.util.StrUtil;
import org.springframework.core.NamedInheritableThreadLocal;
import org.springframework.core.NamedThreadLocal;

import java.util.Objects;

/**
 * @author lipingwei
 * @create 2021-01-27 15:18
 */
public class UserInfoContextHolder {

    public static final ThreadLocal<UserInfo> CONTEXT_HOLDER = new NamedThreadLocal<>("userInfo context holder");
    public static final ThreadLocal<UserInfo> INHERITABLE_CONTEXT_HOLDER = new NamedInheritableThreadLocal<>("inheritable context holder");
    public static final ThreadLocal<String> TOKEN_CONTEXT_HOLDER = new NamedThreadLocal<>("token context holder");
    public static final ThreadLocal<String> INHERITABLE_TOKEN_HOLDER = new NamedInheritableThreadLocal<>("inheritable token holder");
    public static UserInfo getUserInfo(){
        UserInfo userInfo = CONTEXT_HOLDER.get();
        if(Objects.isNull(userInfo)){
           userInfo = INHERITABLE_CONTEXT_HOLDER.get();
        }
        return userInfo;
    }

    public static void setUserInfo(UserInfo userInfo){
        CONTEXT_HOLDER.set(userInfo);
        INHERITABLE_CONTEXT_HOLDER.set(userInfo);
    }

    public static void removeUserInfo(){
        CONTEXT_HOLDER.remove();
        INHERITABLE_CONTEXT_HOLDER.remove();
    }

    public static String getToken(){
        String token = TOKEN_CONTEXT_HOLDER.get();
        if(StrUtil.isBlank(token)){
            token  = INHERITABLE_TOKEN_HOLDER.get();
        }
        return token;
    }

    public static void setToken(String token){
        TOKEN_CONTEXT_HOLDER.set(token);
        INHERITABLE_TOKEN_HOLDER.set(token);
    }

    public  static  void removeToken(){
        TOKEN_CONTEXT_HOLDER.remove();
        INHERITABLE_TOKEN_HOLDER.remove();
    }

}
